package com.ly.mpayment.rest.up.wanlifanghe;

import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import com.ly.mpayment.rest.up.util.Util;
import org.apache.log4j.Logger;
import org.mortbay.util.MultiMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.HashSet;
import java.util.Set;

@Component
@Path("wanlifanghe")
public class WanLiFangHeRest {
    Logger logger = Logger.getLogger(WanLiFangHeRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;


    @Path("callBack")
    @POST
    public String callBack(@RequestBody String data) {
        logger.info("wanlifanghe_callback:" + data);
        if (!StringUtils.isBlank(data)) {
            //szVerifyString=md5(szAgentId=xxx&szOrderId=xxx&szPhoneNum=xxx&nDemo=xxx&fSalePrice=xxx&nFlag=xxx&szKey=xxx) .ToLower()
            JSONObject multiMap = JSONObject.parseObject(data);
            UpOrder order = upOrderService.findById(multiMap.getString("orderid"));
            if(order == null){
                logger.info("订单不存在:"+data);
                return "订单不存在";
            }
            final UpShopInfo upShopInfo = this.upShopInfoService.findByUserId(order.getUserOrder().getUseruuid());
            if(upShopInfo == null){
                logger.info("渠道用户不存在:"+data);
                return "failt";
            }

            //md5(key+parterid+id+orderid+account+amt+state+key
            if(!multiMap.getString("sign").equals(MD5.md5(upShopInfo.getUpkey()+upShopInfo.getAppId()+multiMap.getString("id")+
                    order.getUporderuuid()+
                  multiMap.getString("account")+multiMap.getString("amt")+multiMap.getString("state")
                  +upShopInfo.getUpkey()))){
                logger.info("签名错误:"+data);
                return "failt";
            }

            if (order != null && multiMap.getString("state").equals("0") && order.getStatus() == Config.status[0]) {
                order.setRemark(multiMap.containsKey("sernum") ? multiMap.getString("sernum") : multiMap.getString("state"));
                RechargeRest.successUpOrder.add(order);
                return "success";
            } else if (order != null && order.getStatus() == Config.status[0] && (
                    multiMap.getString("state").equals("2") || multiMap.getString("state").equals("100")
                    )) {
                order.setRemark(multiMap.getString("state"));
                RechargeRest.failtUpOrder.add(order);
                return "success";
            } else {
                this.upOrderService.addOrderMsg(order,multiMap.getString("state"));
                logger.info("wanlifanghe_not_found_order:" + multiMap.getString("account") + "," + (order == null ? "" : order.getUpphonenum()));
            }
        }
        return "0";
    }


    /**
     * 订单提交
     *  必须版本号，当前为  必须商户ID平台提供 必须商户订单号（唯一、不可重复提交最长32位）account必须充值账号amt必须充值金额单位元
     *
     * @param order
     * @param shop
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {

        JSONObject data = new JSONObject();
        data.put("version", "1.0.1");
        data.put("parterid", shop.getAppId());
        data.put("orderid", order.getUporderuuid());
        data.put("account",  order.getUpphonenum());
        data.put("amt", order.getUpShopPro().getUpfacevalue());
        //2edb5b9c-9f99-11e7-9dc0-fcaa1456507e 中国移动
        //2ee16927-9f99-11e7-9dc0-fcaa1456507e 中国联通
        //2ee70961-9f99-11e7-9dc0-fcaa1456507e 中国电信
        data.put("pid", order.getOperators().equals("2edb5b9c-9f99-11e7-9dc0-fcaa1456507e") ? "1" :
                order.getOperators().equals("2ee16927-9f99-11e7-9dc0-fcaa1456507e") ? "2" :
                        order.getOperators().equals("2ee70961-9f99-11e7-9dc0-fcaa1456507e") ? "3" : 4);
        data.put("cid", 1);
        data.put("ts", new DateUtils().toTimeStamp());
        //MD5签名，key由平台提供md5(key+version+parterid+orderid+account+amt+pid+cid+ts+key)
        data.put("sign", MD5.md5(shop.getUpkey()+"1.0.1"+
                shop.getAppId()+
                order.getUporderuuid()+
                order.getUpphonenum()+
                order.getUpShopPro().getUpfacevalue()+
                data.getString("pid") +
                1+
                data.getString("ts")+
                shop.getUpkey()));

        data.put("callbackurl",shop.getOrderCallAddress());
        String result = HttpClient.post(shop.getOrderCommitAddress(), data.toString());
        logger.info("commitOrder_wanlifanghe:" + result + ":" + StringSort.jsonToString(data));
        if (!StringUtils.isBlank(result)) {
            try{
                JSONObject json = JSONObject.parseObject(result);
                if (json.containsKey("code") && json.getString("code").equals("00000")) {
                    this.upOrderService.updateUpOrderMsg(order,json.getJSONObject("result").getString("id"),json.containsKey("msg") ?
                            json.getString("msg") : json.getString("code"));
                } else if (json.containsKey("code") && errorCode.contains(json.getString("code"))){
                    order.setRemark(json.getString("msg"));
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    upOrderService.addOrderMsg(order, json.getString("msg"));
                }
            }catch (Exception e){
                e.printStackTrace();
                upOrderService.updateUpOrderArtificial(order,"","提单失败,人工");
            }
        } else {
            this.upOrderService.updateUpOrder(order, "");
            logger.info("commitOrder_error:" + order.getUpphonenum());
        }
    }

    Set<String> errorCode = new HashSet<String>(){{
        add("10000");
        add("10001");
        add("10002");
        add("10003");
        add("10004");
        add("10005");
        add("10006");
        add("10007");
        add("10008");
        add("10009");
        add("10011");
    }};

    /**
     * 订单查询
     *
     * @param upOrder
     * @param shopInfo
     */
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
        JSONObject data = new JSONObject();
        data.put("version", "1.0.1");
        data.put("parterid", shopInfo.getAppId());
        data.put("orderid", upOrder.getUporderuuid());
        data.put("ts", new DateUtils().toTimeStamp());
        //md5(key+version+parterid+orderid+ts+key)
        data.put("sign", MD5.md5(shopInfo.getUpkey()+"1.0.1"+
                shopInfo.getAppId()+
                upOrder.getUporderuuid()+data.getString("ts")+shopInfo.getUpkey()
                        ));
        String result = HttpClient.post(shopInfo.getOrderStatusAddress(), data.toString());
        logger.info("wanlifanghequeryOrder:" + StringSort.jsonToString(data) + ":" + result);
        if (!StringUtils.isBlank(result)) {
            JSONObject jsonD = JSONObject.parseObject(result);
            if (jsonD.containsKey("code") && jsonD.getString("code").equals("00000")  ) {
                UpOrder order = upOrderService.findById(jsonD.getString("szOrderId"));
                if (order != null && jsonD.getJSONObject("result").getString("state").equals("0") && order.getStatus() == Config.status[0]) {
                    order.setRemark( jsonD.getJSONObject("result").containsKey("sernum") ? jsonD.getJSONObject("result").getString("sernum") :
                            jsonD.containsKey("result") ? jsonD.getString("result") : "");
                    RechargeRest.successUpOrder.add(order);
                } else if (order != null && order.getStatus() == Config.status[0] && (
                        jsonD.getJSONObject("result").getString("state").equals("100") || jsonD.getJSONObject("result").getString("state").equals("2")
                        )) {
                    order.setRemark( jsonD.containsKey("msg") ? jsonD.getString("msg") : "");
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    this.upOrderService.addOrderMsg(order,jsonD.getString("msg"));
                    logger.info("wanlifanghe_not_found_order:" + order.getUpphonenum());
                }
            } else {
                logger.info("wanlifanghe_not_found_order:" + upOrder.getUpphonenum());
            }
        }
    }
}
